package com.qys.livesMall.shop.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qys.livesMall.framework.utils.SecurityUtils;
import com.qys.livesMall.shop.mapper.PurchaseCartMapper;
import com.qys.livesMall.shop.modal.dto.AddPurchaseCartDTO;
import com.qys.livesMall.shop.modal.dto.QueryPurchaseCartDTO;
import com.qys.livesMall.shop.modal.entity.PurchaseCart;
import com.qys.livesMall.shop.modal.vo.PurchaseCartVO;
import com.qys.livesMall.shop.service.PurchaseCartService;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 用户采购购物车(PurchaseCart)表服务实现类
 *
 * @author makejava
 * @since 2023-08-28 11:10:38
 */
@Service("purchaseCartService")
public class PurchaseCartServiceImpl extends ServiceImpl<PurchaseCartMapper, PurchaseCart> implements PurchaseCartService {

    @Override
    public IPage<PurchaseCartVO> selectAll(Long userId, QueryPurchaseCartDTO dto) {
        return baseMapper.selectAllByPage(new Page<>(dto.getPageNum(), dto.getPageSize()), userId);
    }

    @Override
    public synchronized void add(AddPurchaseCartDTO dto) {
        PurchaseCart one = getOne(Wrappers.<PurchaseCart>lambdaQuery().eq(PurchaseCart::getUserId, SecurityUtils.getUserId()).eq(PurchaseCart::getProductSkuId, dto.getProductSkuId()));
        if(one != null){
            one.setQuantity(one.getQuantity() + dto.getQuantity());
            this.updateById(one);
        } else {
            PurchaseCart purchaseCart = new PurchaseCart();
            purchaseCart.setUserId(SecurityUtils.getUserId());
            purchaseCart.setProductSkuId(dto.getProductSkuId());
            purchaseCart.setQuantity(dto.getQuantity());
            this.save(purchaseCart);
        }
    }

    @Override
    public void removePurchaseCart(List<Long> id) {
        baseMapper.deleteBatchIds(id);
    }
}

